package com.aaa.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.aaa.dao.DatabaseDao;
import com.aaa.pojo.User;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * SaResult.ok("登陆成功"); 具体数据: {"code": 200, "msg": "登陆成功", "data": null}
 * 登录控制器
 */

@RestController
@RequestMapping("/user/")
public class SaTokenController {

    @Autowired
    private DatabaseDao databaseDao;

    // 登录
    @RequestMapping("doLogin")
    public SaResult doLogin(@RequestParam("name") String name,@RequestParam("pwd") String pwd) {

        Integer userId = databaseDao.queryUserInfo(name, pwd);
        if (userId != null) {
            StpUtil.login(userId);
            return SaResult.ok("登录成功");
        }

        return SaResult.error("登录失败");
    }

    /* 注解鉴权
    必须登录才能访问
     */
    @RequestMapping("check1")
    @SaCheckLogin
    public String check1() {

        return "1";
    }

    /* 注解鉴权
    必须有 "super-admin" 权限才能访问
     */
    @RequestMapping("check2")
    @SaCheckRole("super-admin")
    public String check2() {

        return "已有 \"super-admin\" 权限";
    }

    /* 注解鉴权
    必须有 "super-admin" 权限才能访问
     */
    @RequestMapping("check3")
    @SaCheckRole("user-add")
    public String check3() {

        return "已有 \"user-add\" 权限";
    }

    @RequestMapping("check4")
    public String check4() {

        boolean b = StpUtil.hasPermission("user.add");
        System.out.println(b);

        if (b) {
            return "通过";
        }else {
            return "不通过";
        }
    }

    // 查询登录状态
    @RequestMapping("isLogin")
    @SaCheckLogin
    public SaResult isLogin() {

        return SaResult.ok("是否登录：" + StpUtil.isLogin());
    }

    // 查询 Token 信息
    @RequestMapping("tokenInfo")
    public SaResult tokenInfo() {

        return SaResult.data(StpUtil.getTokenInfo());
    }

    // 注销
    @RequestMapping("doLogout")
    public SaResult logout() {

        StpUtil.logout();
        return SaResult.ok();
    }

}
